/**
 * 象棋游戏状态管理类
 */

import { INITIAL_BOARD, COLORS, PIECES } from '../constants/pieces.js';
import { GAME_STATUS } from '../constants/gameConfig.js';
import { BOARD_SIZE } from '../constants/positions.js';

export class GameState {
  constructor() {
    this.reset();
  }

  /**
   * 重置游戏状态
   */
  reset() {
    this.board = this.createInitialBoard();
    this.currentPlayer = COLORS.RED; // 红方先行
    this.status = GAME_STATUS.PLAYING;
    this.selectedPosition = null;
    this.validMoves = [];
    this.lastMove = null;
    this.capturedPieces = {
      [COLORS.RED]: [],
      [COLORS.BLACK]: []
    };
    this.moveHistory = [];
    this.moveCount = 0;
    this.isInCheck = {
      [COLORS.RED]: false,
      [COLORS.BLACK]: false
    };
  }

  /**
   * 创建初始棋盘
   */
  createInitialBoard() {
    const board = Array(BOARD_SIZE.ROWS).fill(null).map(() => 
      Array(BOARD_SIZE.COLS).fill(null)
    );

    // 根据INITIAL_BOARD布局创建棋子对象
    for (let row = 0; row < BOARD_SIZE.ROWS; row++) {
      for (let col = 0; col < BOARD_SIZE.COLS; col++) {
        const pieceName = INITIAL_BOARD[row][col];
        if (pieceName) {
          board[row][col] = this.createPiece(pieceName, row, col);
        }
      }
    }

    return board;
  }

  /**
   * 创建棋子对象
   */
  createPiece(name, row, col) {
    // 优化的棋子颜色判断逻辑
    let color = this.determineColorByNameAndPosition(name, row);
    
    const pieceInfo = PIECES[color][name];
    if (!pieceInfo) {
      throw new Error(`无法找到棋子信息: ${name} (${color})`);
    }

    return {
      name,
      color,
      type: pieceInfo.type,
      value: pieceInfo.value,
      symbol: pieceInfo.symbol,
      position: { row, col },
      moveCount: 0 // 移动次数，某些规则可能用到
    };
  }

  /**
   * 根据棋子名称和位置确定颜色
   */
  determineColorByNameAndPosition(name, row) {
    // 明确的红方棋子
    const redPieces = ['帥', '仕', '相', '兵'];
    // 明确的黑方棋子  
    const blackPieces = ['將', '士', '象', '卒'];
    
    if (redPieces.includes(name)) {
      return COLORS.RED;
    } else if (blackPieces.includes(name)) {
      return COLORS.BLACK;
    } else {
      // 车、马、炮根据位置判断
      // 标准象棋布局：0-4行是黑方，5-9行是红方
      return row <= 4 ? COLORS.BLACK : COLORS.RED;
    }
  }

  /**
   * 根据棋子名称判断颜色
   */
  getPieceColor(pieceName) {
    const redPieces = ['帥', '仕', '相', '兵'];
    const blackPieces = ['將', '士', '象', '卒'];
    
    if (redPieces.includes(pieceName)) {
      return COLORS.RED;
    } else if (blackPieces.includes(pieceName)) {
      return COLORS.BLACK;
    } else {
      // 车、马、炮需要根据位置判断颜色
      // 这个方法会在createInitialBoard中调用，需要传入位置信息
      // 暂时返回null，在createPiece中处理
      return null;
    }
  }

  /**
   * 获取指定位置的棋子
   */
  getPieceAt(row, col) {
    if (row < 0 || row >= BOARD_SIZE.ROWS || col < 0 || col >= BOARD_SIZE.COLS) {
      return null;
    }
    return this.board[row][col];
  }

  /**
   * 设置指定位置的棋子
   */
  setPieceAt(row, col, piece) {
    if (row >= 0 && row < BOARD_SIZE.ROWS && col >= 0 && col < BOARD_SIZE.COLS) {
      this.board[row][col] = piece;
      if (piece) {
        piece.position = { row, col };
      }
    }
  }

  /**
   * 移动棋子
   */
  movePiece(from, to) {
    const { row: fromRow, col: fromCol } = from;
    const { row: toRow, col: toCol } = to;
    
    const piece = this.getPieceAt(fromRow, fromCol);
    const targetPiece = this.getPieceAt(toRow, toCol);

    if (!piece) return false;

    // 记录移动历史
    const move = {
      from: { ...from },
      to: { ...to },
      piece: { ...piece },
      capturedPiece: targetPiece ? { ...targetPiece } : null,
      moveNumber: this.moveCount + 1,
      timestamp: Date.now()
    };

    // 如果有被吃的棋子，加入被吃棋子列表
    if (targetPiece) {
      this.capturedPieces[targetPiece.color].push(targetPiece);
    }

    // 执行移动
    this.setPieceAt(fromRow, fromCol, null);
    piece.moveCount++;
    this.setPieceAt(toRow, toCol, piece);

    // 更新游戏状态
    this.lastMove = move;
    this.moveHistory.push(move);
    this.moveCount++;
    this.currentPlayer = this.currentPlayer === COLORS.RED ? COLORS.BLACK : COLORS.RED;

    return true;
  }

  /**
   * 撤销上一步移动
   */
  undoLastMove() {
    if (this.moveHistory.length === 0) return false;

    const lastMove = this.moveHistory.pop();
    const { from, to, piece, capturedPiece } = lastMove;

    // 恢复棋子位置
    this.setPieceAt(from.row, from.col, piece);
    this.setPieceAt(to.row, to.col, capturedPiece);

    // 恢复棋子移动次数
    if (piece) {
      piece.moveCount--;
    }

    // 如果有被吃的棋子，从被吃列表中移除
    if (capturedPiece) {
      const capturedList = this.capturedPieces[capturedPiece.color];
      const index = capturedList.findIndex(p => p.name === capturedPiece.name);
      if (index >= 0) {
        capturedList.splice(index, 1);
      }
    }

    // 更新游戏状态
    this.moveCount--;
    this.currentPlayer = this.currentPlayer === COLORS.RED ? COLORS.BLACK : COLORS.RED;
    this.lastMove = this.moveHistory.length > 0 ? this.moveHistory[this.moveHistory.length - 1] : null;

    return true;
  }

  /**
   * 查找指定颜色的王（帥/將）
   */
  findKing(color) {
    const kingName = color === COLORS.RED ? '帥' : '將';
    
    for (let row = 0; row < BOARD_SIZE.ROWS; row++) {
      for (let col = 0; col < BOARD_SIZE.COLS; col++) {
        const piece = this.getPieceAt(row, col);
        if (piece && piece.name === kingName) {
          return { row, col };
        }
      }
    }
    return null;
  }

  /**
   * 获取指定颜色的所有棋子位置
   */
  getAllPieces(color) {
    const pieces = [];
    
    for (let row = 0; row < BOARD_SIZE.ROWS; row++) {
      for (let col = 0; col < BOARD_SIZE.COLS; col++) {
        const piece = this.getPieceAt(row, col);
        if (piece && piece.color === color) {
          pieces.push({
            piece,
            position: { row, col }
          });
        }
      }
    }
    
    return pieces;
  }

  /**
   * 复制当前游戏状态
   */
  clone() {
    const cloned = new GameState();
    
    // 深拷贝棋盘
    cloned.board = this.board.map(row => 
      row.map(piece => piece ? { ...piece, position: { ...piece.position } } : null)
    );
    
    // 拷贝其他属性
    cloned.currentPlayer = this.currentPlayer;
    cloned.status = this.status;
    cloned.selectedPosition = this.selectedPosition ? { ...this.selectedPosition } : null;
    cloned.validMoves = [...this.validMoves];
    cloned.lastMove = this.lastMove ? { ...this.lastMove } : null;
    cloned.moveCount = this.moveCount;
    cloned.isInCheck = { ...this.isInCheck };
    
    // 拷贝被吃棋子列表
    cloned.capturedPieces = {
      [COLORS.RED]: [...this.capturedPieces[COLORS.RED]],
      [COLORS.BLACK]: [...this.capturedPieces[COLORS.BLACK]]
    };
    
    // 拷贝移动历史
    cloned.moveHistory = this.moveHistory.map(move => ({ ...move }));
    
    return cloned;
  }

  /**
   * 获取当前游戏状态的简要信息
   */
  getGameInfo() {
    return {
      currentPlayer: this.currentPlayer,
      status: this.status,
      moveCount: this.moveCount,
      capturedCount: {
        [COLORS.RED]: this.capturedPieces[COLORS.RED].length,
        [COLORS.BLACK]: this.capturedPieces[COLORS.BLACK].length
      },
      isInCheck: this.isInCheck,
      canUndo: this.moveHistory.length > 0
    };
  }
}
